package com.zyc.app.woa.data;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: yingchang.zhang
 * Date  : 2014/11/28
 */
public class XmlUtils {
    /**
     * 在文档中搜索指定的元素,返回符合条件的元素数组.
     * @param tagName String
     * @return String[]
     */
    public static String[] getElementsByTag(String source, String tagName){
        Pattern p = Pattern.compile("<" + tagName + "[^>]*?((>.*?</" + tagName + ">)|(/>))");
        Matcher m = p.matcher(source);
        ArrayList<String> al = new ArrayList<String>();
        while(m.find()) {
            al.add(m.group());
        }
        String[] arr = al.toArray(new String[al.size()]);
        al.clear();
        return arr;
    }

    /**
     * 获取指定元素的文本内容
     * @param elementString String
     * @return String
     */
    public static String getElementText(String elementString){
        Pattern p = Pattern.compile(".*<!\\[CDATA\\[(.*)\\]\\]>.*");
        Matcher m = p.matcher(elementString);
        if(m.find()){
            return m.group(1);
        }

        p = Pattern.compile(".*>(.*)<.*");
        m = p.matcher(elementString);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }
}
